package com.example.taskschedule.infrastructure.threadPool;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 统计信息收集器
 */
@Slf4j
public class StatisticsCollector {
    private static final AtomicInteger totalTasksProcessed = new AtomicInteger(0);
    private static final AtomicInteger totalTasksRejected = new AtomicInteger(0);
    private static final AtomicInteger maxConcurrentThreads = new AtomicInteger(0);
    private static final AtomicInteger threadPeak = new AtomicInteger(0);
    private static final AtomicLong totalExecutionTime = new AtomicLong(0);
    public static void recordTaskCompletion(long duration){
        totalTasksProcessed.incrementAndGet();
        totalExecutionTime.addAndGet(duration);
    }
    public static void recordTaskRejection(){
        totalTasksRejected.incrementAndGet();
    }
    public static void updateThreadPeak(int currentPoolSize){
        if(currentPoolSize>threadPeak.get()){
            threadPeak.set(currentPoolSize);
        }
    }
    
    public static void updateMaxConcurrentThreads(int activeCount){
        if(activeCount>maxConcurrentThreads.get()){
            maxConcurrentThreads.set(activeCount);
        }
    }
    
    public static void printStatistics(){
        long averageExecutionTime=totalTasksProcessed.get()>0
                ?totalExecutionTime.get()/totalTasksProcessed.get()
                :0;
        log.info("========统计结果=======");
        log.info("总共处理任务数：{}", totalTasksProcessed.get());
        log.info("总共拒绝任务数：{}", totalTasksRejected.get());
        log.info("最大并发线程数：{}", maxConcurrentThreads.get());
        log.info("平均处理任务耗时：{} ms", averageExecutionTime);
        log.info("线程峰值数：{}", threadPeak.get());
    }
    
    
}
